package com.sqx.modules.health.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.modules.health.common.Constants;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.entity.NcgServiceorder;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.health.service.INcgServiceService;
import com.sqx.modules.health.service.INcgServiceorderService;
import com.sqx.modules.health.service.IUserAddressService;
import com.sqx.modules.health.service.IUserService;
import com.sqx.modules.health.utils.MyBeanUtil;
import com.sqx.modules.health.vo.NcgServiceOrderVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 预订服务 前端控制器
 * </p>
 *
 * @author gxy
 * @since 2022-04-08
 */

@Slf4j
@Api(value = "预订服务", tags = "预订服务", description = "")
@RestController
@RequestMapping("/health/ncgServiceOrder")
public class NcgServiceorderController {
    @Autowired
    private INcgServiceorderService ncgServiceorderService;

    @Autowired
    private IUserService userService;

    @Autowired
    private INcgServiceService service;

    @Autowired
    private IUserAddressService addressService;

    // 新增或更新
    @PostMapping("/save")
    @ApiOperation(value = "新增或更新预订服务(小程序)", notes = "新增或更新预订服务(小程序)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "预约服务状态id", paramType = "Integer"),
            @ApiImplicitParam(name = "uid", value = "患者id", paramType = "Integer"),
            @ApiImplicitParam(name = "sid", value = "服务的id", paramType = "Integer"),
            @ApiImplicitParam(name = "status", value = "支付状态(0未支付 1已接单 3完成 9撤销 默认为0)", paramType = "Integer"),
            @ApiImplicitParam(name = "score", value = "评分", paramType = "decimal"),
            @ApiImplicitParam(name = "evaluate", value = "评价", paramType = "String"),
            @ApiImplicitParam(name = "isscore", value = "用户是否评分", paramType = "Integer"),
            @ApiImplicitParam(name = "planservicetime", value = "计划服务时间", paramType = "String"),
            @ApiImplicitParam(name = "submittime", value = "提交时间", paramType = "String"),
            @ApiImplicitParam(name = "servicetime", value = "服务时间", paramType = "String"),
            @ApiImplicitParam(name = "isdelete", value = "是否删除 0:否 1:是", paramType = "Integer"),
            @ApiImplicitParam(name = "createtime", value = "创建时间", paramType = "String"),
            @ApiImplicitParam(name = "updatetime", value = "更新时间", paramType = "String"),
            @ApiImplicitParam(name = "addressid", value = "地址id", paramType = "Long"),
            @ApiImplicitParam(name = "remark", value = "订单备注(主诉)", paramType = "string"),
            @ApiImplicitParam(name = "accepter", value = "订单处理人id", paramType = "Long"),
            @ApiImplicitParam(name = "hid", value = "医院id", paramType = "Long"),
            @ApiImplicitParam(name = "prove", value = "就诊证明", paramType = "string"),
            @ApiImplicitParam(name = "proveimg", value = "就诊证明图片 --> 多个就传集合", paramType = "string"),
    })
    public Result save(@RequestBody NcgServiceorder ncgServiceorder) {
        if (ncgServiceorder.getId() == null) {
            if (ncgServiceorder.getProveimgList().size() != 0) {
                ncgServiceorder.setProveimg("[" + convertListToString(ncgServiceorder.getProveimgList()) + "]");
            }
            // 新增操作 设置默认值
            ncgServiceorder.setIsscore(0); // 评分状态为未评分
            ncgServiceorder.setSubmittime(LocalDateTime.now()); // 设置提交时间为当前时间
            ncgServiceorder.setCreatetime(LocalDateTime.now()); // 设置创建时间为当前时间
            ncgServiceorder.setIsdelete(0); // 设置删除状态为 未删除
            ncgServiceorder.setStatus(ncgServiceorder.getStatus() == null ? 0 : ncgServiceorder.getStatus()); // 如果没有传评分默认为0
        } else {
            // 修改操作
            ncgServiceorder.setUpdatetime(LocalDateTime.now()); // 设置修改时间为当前时间
        }
        return Result.success(ncgServiceorderService.saveOrUpdate(ncgServiceorder));
    }

    public static String convertListToString(List<String> strList) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < strList.size(); i++) {
            if (i == 0) {
                sb.append("'").append(strList.get(i)).append("'");
            } else {
                sb.append(",").append("'").append(strList.get(i)).append("'");
            }
        }
        return sb.toString();
    }

    @PostMapping("/webSave")
    @ApiOperation(value = "新增或更新预订服务(web端)", notes = "新增或更新预订服务(web端)")
    public Result webSave(@RequestBody NcgServiceOrderVo ncgServiceOrderVo) {
        ncgServiceOrderVo.setUpdatetime(LocalDateTime.now()); // 设置修改时间为当前时间
        NcgServiceorder order = new NcgServiceorder();
        BeanUtil.copyProperties(ncgServiceOrderVo, order);
        return Result.success(ncgServiceorderService.saveOrUpdate(order));
    }

    // 根据ID删除
    @GetMapping("/del/{id}")
    @ApiOperation(value = "根据ID删除预订服务", notes = "根据ID删除预订服务")
    public Result delete(@PathVariable Integer id) {
        return Result.success(ncgServiceorderService.removeById(id));
    }

    // 根据IDS删除
    @GetMapping("/del/batch")
    @ApiOperation(value = "根据IDS删除预订服务", notes = "根据IDS删除预订服务")
    public Result deleteBatch(@RequestParam List<Integer> ids) {
        return Result.success(ncgServiceorderService.removeByIds(ids));
    }

    // 查询全部
    @GetMapping("/findAll")
    @ApiOperation(value = "查询全部预订服务", notes = "查询全部预订服务")
    public Result findAll() {
        return Result.success(ncgServiceorderService.list());
    }

    // 根据ID查询一条记录
    @GetMapping("/findOne")
    @ApiOperation(value = "根据ID查询一条记录预订服务", notes = "根据ID查询一条记录预订服务")
    public Result findOne(@RequestParam Integer id) {
        NcgServiceorder byId = ncgServiceorderService.getById(id);
        byId.setProveimgList(converStringToList(byId.getProveimg()));
        return Result.success(byId);
    }

    public static List<String> converStringToList(String strs) {
        if (StringUtils.isNotBlank(strs)) {
            String[] idStrs = strs.replace("'", "").replace("[", "").replace("]", "").trim().split(",");
            if (idStrs.length > 0) {
                List<String> strsList = new ArrayList<String>();
                for (String str : idStrs) {
                    if (StringUtils.isNotBlank(str)) {
                        strsList.add(str.trim());
                    }
                }
                if (strsList.size() > 0) {
                    return strsList;
                }
            }
        }
        return null;
    }

    // 分页查询
    @GetMapping("/findPage")
    @ApiOperation(value = "分页查询预订服务", notes = "分页查询预订服务")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(required = false, defaultValue = "") Long uid,
                           @RequestParam(required = false, defaultValue = "") Long sid,
                           @RequestParam(required = false, defaultValue = "") Integer status,
                           @RequestParam(required = false, defaultValue = "") Long accepter,
                           @RequestParam(required = false, defaultValue = "") String planservicetime,
                           @RequestParam(required = false, defaultValue = "") Long hid,
                           @RequestParam(required = false, defaultValue = "") String receptor) {
        QueryWrapper<NcgServiceorder> queryWrapper = new QueryWrapper<>();
        // 拼接查询条件
        if (ObjectUtil.isNotEmpty(uid)) {
            queryWrapper.eq("uid", uid);
        }
        if (ObjectUtil.isNotEmpty(sid)) {
            queryWrapper.eq("sid", sid);
        }
        if (ObjectUtil.isNotEmpty(status)) {
            queryWrapper.eq("status", status);
        }
        if (ObjectUtil.isNotEmpty(accepter)) {
            queryWrapper.eq("accepter", accepter);
        }
        if (ObjectUtil.isNotEmpty(hid)) {
            queryWrapper.eq("hid", hid);
        }
        if (planservicetime != null && StringUtils.isNotEmpty(planservicetime)) {
            // 预定时间小于前端发送时间 表示当前服务可以被接单
            queryWrapper.ge("planservicetime", planservicetime);
        }
        if (ObjectUtil.isNotEmpty(receptor)) {
            queryWrapper.like("receiptor", receptor);
        }
        queryWrapper.orderByDesc("createtime");
        Page<NcgServiceorder> page = ncgServiceorderService.page(new Page<>(pageNum, pageSize), queryWrapper);
        // 将查询到的数据copy 到一个新的集合中 作为定制化数据返回前端
        List<NcgServiceOrderVo> ncgServiceOrderVos = MyBeanUtil.collectionCopy(page.getRecords(), NcgServiceOrderVo.class);
        Page<NcgServiceOrderVo> result = new Page<>();
        result.setRecords(ncgServiceOrderVos);
        // 将查询到的数据直接封装到vo中
        result.setTotal(page.getTotal());
        for (NcgServiceOrderVo orderVo : result.getRecords()) {
            orderVo.setProveimgList(converStringToList(orderVo.getProveimg()));
            // 根据患者的id 查询患者的名称
            if (ObjectUtil.isNotEmpty(orderVo.getUid())) {
                SysUserEntity user = userService.getRedisByUid(orderVo.getUid());
                if (!ObjectUtil.isEmpty(user)) {
                    orderVo.setUName(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName());
                }
            }
            // 根据服务的id 查询服务的名称
            if (ObjectUtil.isNotEmpty(orderVo.getSid())) {
                orderVo.setSName((service.getById(orderVo.getSid())).getName());
                orderVo.setService(service.getById(orderVo.getSid()));
            }
            // 根据地址的id 获取地址信息
//            if (ObjectUtil.isNotEmpty(orderVo.getAddressid())) {
//                UserAddress userAddress = addressService.getById(orderVo.getAddressid());
//                if (ObjectUtil.isNotEmpty(userAddress)) {
//                    orderVo.setAddress(userAddress.getAddress());
//                }
//            }
            if (ObjectUtil.isNotEmpty(orderVo.getAccepter())) {
                // 根据接单人id 去用户表查出该用户
                SysUserEntity user = userService.getRedisByUid(orderVo.getAccepter());
                if (ObjectUtil.isNotEmpty(user)) {
                    orderVo.setAccepterName(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName());
                    orderVo.setGender(user.getGender());
                }
            }
        }
        return Result.success(result);
    }

    @ApiOperation("医护人员接单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "接单人 ==> 当前登录人", paramType = "Long"),
            @ApiImplicitParam(name = "orderId", value = "订单ID", paramType = "Long"),
    })
    @GetMapping("/receiving")
    public Result receiving(@RequestParam(required = false, defaultValue = "") Long uid,
                            @RequestParam(required = false, defaultValue = "") Long orderId) {

        if (ObjectUtil.isEmpty(uid) || ObjectUtil.isEmpty(orderId)) {
            return Result.error(Constants.CODE_500, "参数错误");
        }
        NcgServiceorder byId = ncgServiceorderService.getById(orderId);
        if (ObjectUtil.isEmpty(byId)) {
            return Result.error(Constants.CODE_500, "订单不存在");
        }
        if (ObjectUtil.isNotEmpty(byId.getAccepter()) && byId.getStatus() != 0) {
            return Result.error(Constants.CODE_500, "该订单已被接单");
        }
        LambdaUpdateWrapper<NcgServiceorder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(NcgServiceorder::getAccepter, uid);
        updateWrapper.set(NcgServiceorder::getStatus, 1);
        updateWrapper.eq(NcgServiceorder::getId, orderId);
        boolean update = ncgServiceorderService.update(updateWrapper);
        if (!update) {
            return Result.error(Constants.CODE_500, "接单失败");
        }
        return Result.success("接单成功");
    }

    @ApiOperation("订单评价")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单ID", paramType = "Long"),
            @ApiImplicitParam(name = "score", value = "评分", paramType = "BigDecimal"),
            @ApiImplicitParam(name = "evaluate", value = "评价内容", paramType = "String"),
    })
    @GetMapping("/appraise")
    public Result appraise(@RequestParam Long orderId,
                           @RequestParam(required = false, defaultValue = "5.00") BigDecimal score,
                           @RequestParam(required = false, defaultValue = "") String evaluate) {
        if (ObjectUtil.isEmpty(orderId)) {
            return Result.error(Constants.CODE_500, "参数错误");
        }
        NcgServiceorder serviceorder = ncgServiceorderService.getById(orderId);
        if (ObjectUtil.isEmpty(serviceorder)) {
            return Result.error(Constants.CODE_500, "订单不存在");
        }
        if (ObjectUtil.notEqual(2, serviceorder.getStatus())) {
            return Result.error(Constants.CODE_500, "订单未完成,不可评价!!");
        }
        LambdaUpdateWrapper<NcgServiceorder> wrapper = new LambdaUpdateWrapper<NcgServiceorder>()
                .set(NcgServiceorder::getScore, score)
                .set(NcgServiceorder::getEvaluate, evaluate)
                .set(NcgServiceorder::getIsscore, 1)
                .eq(NcgServiceorder::getId, orderId);

        boolean result = ncgServiceorderService.update(wrapper);
        if (result) {
            return Result.success("评价成功");
        } else {
            return Result.error(Constants.CODE_500, "评价失败!!");
        }
    }

    @ApiOperation("我的账单 不传日期默认查全部")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accepter", value = "医护id", paramType = "Long"),
            @ApiImplicitParam(name = "StartTime", value = "开始时间", paramType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "String"),
    })
    @GetMapping("/countOrder")
    public Result countOrder(@RequestParam Long accepter,
                             @RequestParam(required = false, defaultValue = "") String StartTime,
                             @RequestParam(required = false, defaultValue = "") String endTime) {

       QueryWrapper<NcgServiceorder> wrapper = new QueryWrapper<NcgServiceorder>()
               .eq(ObjectUtil.isNotEmpty(accepter), "accepter", accepter)
               .between(ObjectUtil.isNotEmpty(StartTime) && ObjectUtil.isNotEmpty(endTime),
                       "servicetime", StartTime.replace("/", "-"), endTime.replace("/", "-"))
               .eq("status", 2);
        List<NcgServiceorder> ncgServiceorders = ncgServiceorderService.list(wrapper);
        BigDecimal amount = new BigDecimal(0);
        for (NcgServiceorder ncgServiceorder : ncgServiceorders) {
            amount = amount.add(ncgServiceorder.getOrderAmount());
        }
        JSONObject result = new JSONObject();
        result.put("count", ncgServiceorders.size());
        result.put("amount", amount);
        return Result.success(result);
    }


}

